package com.vote.services.impl;

import org.apache.log4j.Logger;

import java.io.Serializable;
import java.util.Date;

import net.sf.ehcache.Cache;
import net.sf.ehcache.Element;

import com.vote.services.CacheService;

public class CacheServiceEhcacheImpl implements CacheService {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(CacheServiceEhcacheImpl.class);
	
	private Cache localCache;
	
	public Cache getLocalCache() {
		return localCache;
	}

	public void setLocalCache(Cache localCache) {
		this.localCache = localCache;
	}

	public void init(){
		
	}
	
	public void destroy(){
		
	}

	@Override
	public boolean exist(String key) {
		if(key == null || "".equalsIgnoreCase(key)){
			logger.info("check exist in cache but key == null or key = \"\".");
			return false;
		}
		return localCache.isKeyInCache(key);
	}

	@Override
	public Object get(String key) {
		if(key == null || "".equalsIgnoreCase(key)){
			logger.info("get key from cache but key == null or key = \"\".");
			return null;
		}
		Element element = null;
		element = localCache.get(key);
		if(element == null){
			return null;
		}else{
			return element.getValue();
		}
	}

	@Override
	public void remove(String key) {
		if(key == null || "".equalsIgnoreCase(key)){
			logger.info("remove key from cache but key == null or key = \"\".");
			return;
		}
		localCache.remove(key);
	}

	@Override
	public void set(String key, Serializable value) {
		if(key == null || "".equalsIgnoreCase(key)){
			logger.info("set key in cache but key == null or key = \"\".");
			return;
		}
		if(value == null){
			logger.info("set value in cache but value == null or value = \"\".");
			return;
		}
		localCache.put(new Element(key, value));
	}

	@Override
	public void set(String key, Serializable value, long time) {
		if(key == null || "".equalsIgnoreCase(key)){
			logger.info("remove key from cache but key == null or key = \"\".");
			return;
		}
		if(value == null){
			logger.info("set value in cache but value == null or value = \"\".");
			return;
		}
		localCache.put(new Element(key, value));
	}

}
